package com.sita.linboard.driverInfo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sita.linboard.R;
import com.sita.linboard.base.ActivityCollector;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.login.RegisterThirdActivity;
import com.sita.linboard.person.SettingBackBean;
import com.sita.linboard.utils.BitmapUtils;
import com.sita.linboard.utils.ConstantValues;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import java.io.File;

import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

/**
 * Created by Jason on 2016/9/2.
 */
public class DriverSetInfoActivity extends BaseActivity implements View.OnClickListener {
    private static final int TAKE_PHOTO_REQUEST_CODE = 1;
    private static boolean isShowPop = true;
    private static boolean isAccountChanged;
    private TextView headTitle, driversex, driverphone, drivertype, driverssn;
    private LinearLayout back;
    private EditText drivername;
    private SettingBackBean backBean;
    private ImageView driver_img;
    private ImageView sex_choose, type_choose;
    private PopupWindow popupWindow;
    private PopupWindow typePop;
    private Button upData;
    private LinearLayout updataLayout;
    private Bitmap bitmap;
    private Uri imageUri;
    private File DriverIConFile;
    private UpDataDriverRequest request;

    public static void DriverIntent(Context context, SettingBackBean backBean) {
        Intent intent = new Intent(context, DriverSetInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("Settingbean", backBean);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
        request = new UpDataDriverRequest();

        backBean = (SettingBackBean) getIntent().getSerializableExtra("Settingbean");
        if (backBean == null) {
            ToastUtils.show("请检查网络是否异常", 3);
            finish();
        }
        setDirverInfo(backBean);

    }

    private void setDirverInfo(SettingBackBean backBean) {
        try {
            Picasso.with(BaseApplication.getContext()).load(backBean.getData().getAccount().getAvatar()).into(driver_img);
        } catch (IllegalArgumentException exception) {

        }

        if (backBean.getData().getAccount().getNickName() != null) {
            drivername.setText(backBean.getData().getAccount().getNickName().toString());
        }
        if (backBean.getData().getAccount().getMobile() != null) {
            driverphone.setText(backBean.getData().getAccount().getMobile().toString());
        }

        if (backBean.getData().getAccount().getDriver().getType() == 1) {
            drivertype.setText("身份证");
            request.gender = 1;
        }
        if (backBean.getData().getAccount().getDriver().getSsn() != null) {
            driverssn.setText(backBean.getData().getAccount().getDriver().getSsn().toString());
        }
        if (backBean.getData().getAccount().getGender() == 1) {
            driversex.setText("男");
        } else {
            driversex.setText("女");
        }
    }

    private void UpDataInfo(UpDataBackBean backBean) {
        Picasso.with(BaseApplication.getContext()).load(backBean.getData().getAvatar()).into(driver_img);
        if (backBean.getData().getNickName() != null) {
            drivername.setText(backBean.getData().getNickName().toString());
        }
        if (backBean.getData().getMobile() != null) {
            driverphone.setText(backBean.getData().getMobile().toString());
        }
        if (backBean.getData().getGender() == 1) {
            driversex.setText("男");
        } else {
            driversex.setText("女");
        }

    }

    @Override
    protected void initData() {
        headTitle.setText("个人资料");
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        upData.setOnClickListener(this);
        driver_img.setOnClickListener(this);

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        headTitle = bindView(R.id.head_title);
        back = bindView(R.id.img_back);
        drivername = bindView(R.id.driver_name);
        drivername.setSelection(drivername.getText().length());
        driversex = bindView(R.id.driver_sex);
        driverphone = bindView(R.id.driver_phone);
        drivertype = bindView(R.id.driver_type);
        driverssn = bindView(R.id.driver_ssn);
        driver_img = bindView(R.id.driver_img);
        sex_choose = bindView(R.id.choose_sex);
        upData = bindView(R.id.updata_msg);
        updataLayout = bindView(R.id.updata_layout);
//        type_choose.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (isShowPop){
//                   // showTypePop(v);
//                    isShowPop = false;
//                }
//                else {
//                    typePop.dismiss();
//                    isShowPop = true;
//                }
//
//            }
//        });
        sex_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPop) {
                    showPop(v);
                    isShowPop = false;
                } else {
                    popupWindow.dismiss();
                    isShowPop = true;
                }

            }
        });
    }

    //    private void showTypePop(View view){
//        LinearLayout linearLayout = new LinearLayout(this);
//        linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.type_menu,null);
//        typePop = new PopupWindow(linearLayout,150, LinearLayout.LayoutParams.WRAP_CONTENT);
//        typePop.setFocusable(false);
//        typePop.setOutsideTouchable(true);
//        typePop.setBackgroundDrawable(new BitmapDrawable());
//        int[] location = new int[2];
//        view.getLocationOnScreen(location);
//        typePop.showAtLocation(view, Gravity.NO_GRAVITY, location[0]-typePop.getWidth(), location[1]+25);
//        final TextView ssn = (TextView) linearLayout.findViewById(R.id.driver_ssn);
//        ssn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                drivertype.setText(ssn.getText().toString());
//                typePop.dismiss();
//                isShowPop = true;
//            }
//        });
//        final TextView passport = (TextView) linearLayout.findViewById(R.id.driver_pass);
//        passport.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                drivertype.setText(passport.getText().toString());
//                typePop.dismiss();
//                isShowPop = true;
//            }
//        });
//    }
    private void showPop(View v) {
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.pop_menu, null);
        popupWindow = new PopupWindow(linearLayout, 150, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0] - popupWindow.getWidth(), location[1] + 25);
        final TextView textMan = (TextView) linearLayout.findViewById(R.id.man);
        textMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                driversex.setText(textMan.getText().toString());
                request.gender = 1;
                popupWindow.dismiss();
                isShowPop = true;
            }
        });
        final TextView textWoman = (TextView) linearLayout.findViewById(R.id.woman);
        textWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                driversex.setText(textWoman.getText().toString());
                request.gender = 2;
                popupWindow.dismiss();
                isShowPop = true;
            }
        });
    }

    @Override
    protected int getId() {

        return R.layout.activity_setinfo;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.updata_msg:
                UpDataMsg();
                break;
            case R.id.driver_img:
                if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    String[] mPermissionList = new String[]{Manifest.permission.CAMERA};
                    ActivityCompat.requestPermissions(DriverSetInfoActivity.this, mPermissionList, 123);
                }
                showPopWindow();//参数可不理会

                break;
        }
    }

    /**
     * 升级用户信息
     */

    private void UpDataMsg() {
        if (drivername.getText().length() == 0 || driversex.getText().length() == 0) {
            ToastUtils.show("用户资料填写不完整", 3);
            return;
        } else {
            request.accountId = SpUtils.getString("AccoundID", null, BaseApplication.getContext());
            request.nickName = drivername.getText().toString();
            String resStr = RestClient.getGson().toJson(request);
            TypedString string = new TypedString(resStr);
            TypedFile file = new TypedFile("DriverIcon", reverseimgSace());
            RestClient.getRestService().upData(string, file, new Callback<UpDataBackBean>() {
                @Override
                public void success(UpDataBackBean settingBackBean, Response response) {
                    if (settingBackBean.getErrorCode().equals("0")) {
                        ToastUtils.show("资料更新成功", 3);
                        UpDataInfo(settingBackBean);
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    ToastUtils.show("更新失败", 3);
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap != null) {
            bitmap.recycle();
        }
        System.gc();

    }

    @Override
    protected void onPause() {
        super.onPause();
        ActivityCollector.removeActivity(this);
    }

    private void showPopWindow() {

        final PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_popwindows, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);//item是否相应点击事件
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(updataLayout, Gravity.BOTTOM, 0, 0);
        popupWindow.update();
        Button btCam = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button btCancle = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        btCam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入相机
                clickTakePhoto();
                popupWindow.dismiss();
            }
        });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入相册
                clickPickFromGallery();
                popupWindow.dismiss();
            }
        });
        btCancle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 进入相机
     *
     * @param
     */
    private void clickTakePhoto() {
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            EasyImage.openCamera(this, 0);
            getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, RegisterThirdActivity.AppState.IN_CAMERA_PHOTO.name());
        } else {
            Nammu.askForPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    EasyImage.openCamera(DriverSetInfoActivity.this, 0);
                    //
                    getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, RegisterThirdActivity.AppState.IN_CAMERA_PHOTO.name());
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }

    protected void clickPickFromGallery() {
        /** Some devices such as Samsungs which have their own gallery app require write permission. Testing is advised! */
        getIntent().putExtra(ConstantValues.BUNDLE_APP_STATE, RegisterThirdActivity.AppState.IN_CAMERA_PHOTO.name());
        EasyImage.openGallery(this, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePicked(File file, EasyImage.ImageSource imageSource, int i) {
                isAccountChanged = true;
                imageUri = Uri.fromFile(file);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                /**
                 * 这段代码将图片的大小进行缩小
                 */
                BitmapFactory.decodeFile(file.toString(), options);
                // options.inSampleSize = calculateInSampleSize(options, 94, 94);
                final int height = options.outHeight;
                final int width = options.outWidth;
                options.inSampleSize = 1;
                int w = 320;
                int h = 480;
                h = w * height / width;//计算出宽高等比率
                int a = options.outWidth / w;
                int b = options.outHeight / h;
                options.inSampleSize = Math.max(a, b);
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeFile(file.toString(), options);
                driver_img.setImageBitmap(bitmap);
                driver_img.setTag("DriverIcon");

            }

            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
                super.onImagePickerError(e, source, type);
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source, int type) {
                super.onCanceled(source, type);
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(DriverSetInfoActivity.this);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    private File reverseimgSace() {
        String DRIVER_IMG = "Driver_icon_img";
        //   if (vehicle_end.getB)
        DriverIConFile = BitmapUtils.saveBmpFile(((BitmapDrawable) driver_img.getDrawable()).getBitmap(), DRIVER_IMG);
        return DriverIConFile;
    }

    public enum AppState {
        FROM_LAUNCH,
        IN_FOREGROUND,
        IN_BACKGROUND,
        IN_CAMERA_PHOTO
    }
}
